using System;
using System.Windows;
using MiniTheme.Services.Interfaces;

namespace MiniTheme.Services;

// 语言服务实现，负责动态切换应用程序语言
public class LanguageService : ILanguageService
{
    private string _currentLanguage = "zh-CN";  // 当前语言
    private readonly IConfigService _configService;

    public LanguageService(IConfigService configService)
    {
        _configService = configService;
    }
    // 应用指定的语言
    public void ApplyLanguage(string languageCode)
    {
        // 移除所有旧的语言资源字典(同一个资源字典是可以添加多次的，必须全部移除)
        var oldLanguageDict = Application.Current.Resources.MergedDictionaries
            .FirstOrDefault(d => d.Source != null && d.Source.OriginalString.Contains("Resources/Languages/"));
        if (oldLanguageDict != null)
        {
            Application.Current.Resources.MergedDictionaries.Remove(oldLanguageDict);
        }
        // 加载新的语言资源字典
        var languagePath = $"Resources/Languages/{languageCode}.xaml";
        var languageDict = new ResourceDictionary
        {
            Source = new Uri(languagePath, UriKind.Relative)
        };
        Application.Current.Resources.MergedDictionaries.Add(languageDict);
        _currentLanguage = languageCode;
        // 将修改同步到配置文件中
        _configService.SaveLanguage(languageCode);  
    }
    // 获取当前语言
    public string GetCurrentLanguage()
    {
        return _currentLanguage;
    }
}
